package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.ResultMap;
import cn.lijinquan.p2p.entites.User;
import cn.lijinquan.p2p.entites.UserAcount;
import com.lijinquan.springcloud.constants.FrontStatusConstants;
import com.lijinquan.springcloud.utils.CommomUtil;
import com.lijinquan.springcloud.utils.ImageUtil;
import com.lijinquan.springcloud.utils.MD5Util;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lijinquan on 2019/5/26.
 */

@RestController
@EnableEurekaClient
public class UserControllerConsumer {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String REST_URL_PREFIX = "http://P2P-WEB/";
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取uuid
     *
     * @return
     */
    @RequestMapping(value = "/user/uuid")
    public ResultMap<String> getUuid() {
        ResultMap<String> rmp = new ResultMap<>();
        String uuid = restTemplate.getForObject(REST_URL_PREFIX + "user/uuid", String.class);
        rmp.setBody(uuid);
        if (StringUtils.isEmpty(uuid)) {
            rmp.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rmp;
        }
        return rmp;

    }

    /**
     * 获取验证码图片
     *
     * @param response
     * @param session
     * @param request
     * @throws IOException
     */
    @RequestMapping("/user/validateCode")
    public void getImg(HttpServletResponse response, HttpSession session, HttpServletRequest request) throws IOException {
        String tokenUuid = request.getParameter("tokenUuid");
        String time = request.getParameter("time");
        String str = restTemplate.getForObject(REST_URL_PREFIX + "user/validateCode/" + tokenUuid, String.class);
        if (StringUtils.isEmpty(str)) {
            return;
        }
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        ImageUtil.getImage(str, response.getOutputStream());
    }

    /**
     * 校验用户名
     *
     * @param request
     * @return
     */
    @RequestMapping("/user/validateUserName")
    public ResultMap<User> validateUserName(HttpServletRequest request) {
        ResultMap<User> rmp = new ResultMap<>();
        String username = request.getParameter("username");
        User user = new User();
        if (StringUtils.isEmpty(username)) {
            rmp.setBody(user);
            rmp.setCode("Fail");
            rmp.setStatus(FrontStatusConstants.BREAK_DOWN);
        }
        user.setUsername(username);
        User u = restTemplate.postForObject(REST_URL_PREFIX + "user/findByUserCondition/", user, User.class);
        rmp.setBody(u);
        if (u != null) {
            rmp.setStatus(FrontStatusConstants.ALREADY_EXIST_OF_USERNAME); // 用户名状态码为70说明用户名被占用
            rmp.setCode("Fail");
            return rmp;
        }
        return rmp;
    }

    /**
     * 校验手机号
     *
     * @param request
     * @return
     */
    @RequestMapping("/user/validatePhone")
    public ResultMap<Boolean> validatePhone(HttpServletRequest request) {
        ResultMap<Boolean> rmp = new ResultMap<>();
        String phone = request.getParameter("phone");
        if (StringUtils.isEmpty(phone)) {
            rmp.setBody(false);
            rmp.setCode("Fail");
            rmp.setStatus(FrontStatusConstants.NULL_OF_MOBILE_NO);
        }
        Boolean b = restTemplate.getForObject(REST_URL_PREFIX + "user/validatePhone/" + phone, Boolean.class);
        rmp.setBody(b);
        if (!b) {
            rmp.setStatus(FrontStatusConstants.BREAK_DOWN);
            rmp.setCode("Fail");
            return rmp;
        }
        return rmp;
    }


    /**
     * 校验验证码
     */
    @RequestMapping("/user/codeValidate")
    public ResultMap<String> codeValidate(HttpServletRequest request) {
        ResultMap<String> rmp = new ResultMap<>();
        String signUuid = request.getParameter("signUuid");
        String signCode = request.getParameter("signCode");
        if (StringUtils.isEmpty(signUuid) || StringUtils.isEmpty(signCode)) {
            rmp.setBody(null);
            rmp.setCode("Fail");
            rmp.setStatus(FrontStatusConstants.NULL_OF_VALIDATE_CARD); // 验证码为空
        }
        String value = restTemplate.getForObject(REST_URL_PREFIX + "user/codeValidate/" + signUuid, String.class);
        rmp.setBody(value);
        if (StringUtils.isEmpty(value) || !value.toUpperCase().equals(signCode.toUpperCase())) {
            rmp.setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD);
            rmp.setCode("Fail");
        } else {
            logger.info("======> Code Validate is true!");
        }

        return rmp;
    }


    @RequestMapping("/user/signup")
    public ResultMap<Map<String, String>> rigister(HttpServletRequest request) {
        ResultMap<Map<String, String>> rmp = new ResultMap<>();
        Map<String, String> res = new HashMap<>();
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        //String invitCode = request.getParameter("inviteId");//邀请码
        String uuid = request.getParameter("signUuid");
        String captcha = request.getParameter("signCode"); // 验证码
        String s = validateRegisterParams(username, phone, password);
        logger.info("======> Validate register parameters !");
        if (!StringUtils.isEmpty(s)) {
            rmp.setBody(null);
            rmp.setCode("Fail");
            rmp.setStatus(FrontStatusConstants.BREAK_DOWN);
            rmp.setMassage("uuid is null !");
            logger.info("======> Validate register parameters is fail !");
            return rmp;
        }
        // 验证uuid
        String value = restTemplate.getForObject(REST_URL_PREFIX + "user/codeValidate/" + uuid, String.class);
        if (StringUtils.isEmpty(value) || !value.toUpperCase().equals(captcha.toUpperCase())) {
            rmp.setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD);
            rmp.setCode("Fail");
            rmp.setMassage("Validate uuid or token is fail !");
            return rmp;
        }
        logger.info("======> CodeValidate is true!");
        //所有验证通过后
        User user = new User();
        user.setUsername(username);
        user.setPhone(phone);
        user.setPassword(password);
        //user.setInviteid(invitCode);
        user.setRegisterTime(new Date());
        //开始注册
        User u = restTemplate.postForObject(REST_URL_PREFIX + "user/register/", user, User.class);
        // 获取token
        String token = restTemplate.getForObject(REST_URL_PREFIX + "user/generateUserToken/" + username, String.class);
        UserAcount userAcount = new UserAcount();
        userAcount.setUserId(u.getId());
        Boolean b = restTemplate.postForObject(REST_URL_PREFIX + "user/addUserAcount/", userAcount, Boolean.class);
        if (u.getId() > 0 && b && token == null) {
            rmp.setCode("Fail");
            rmp.setStatus(FrontStatusConstants.REGISTER_LOSED);
            return rmp;
        }
        res.put("token", token);
        res.put("uid", String.valueOf(u.getId()));
        rmp.setBody(res);
        return rmp;
    }


    public String validateRegisterParams(String username, String phone, String password) {
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isEmpty(username)) {
            sb.append("用户名不能为空!");
        } else if (StringUtils.isEmpty(phone)) {
            sb.append("手机号不能为空！");
        } else if (StringUtils.isEmpty(password)) {
            sb.append("密码不能为空！");
        }
        return sb.toString();
    }

    @RequestMapping("/user/login")
    public ResultMap<Map<String, Object>> login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String signUuid = request.getParameter("signUuid");
        String signCode = request.getParameter("signCode");
        ResultMap<Map<String, Object>> rm = new ResultMap<>();
        Map<String, Object> res = new HashMap<>();
        User user = new User();
        //验证验证码
        String value = restTemplate.getForObject(REST_URL_PREFIX + "user/codeValidate/" + signUuid, String.class);
        if (StringUtils.isEmpty(value) || !value.equalsIgnoreCase(signCode)) {
            rm.setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD);
            rm.setCode("Fail");
            logger.info("======> User login Validate Code failde !");
            return rm;
        }

        if (CommomUtil.isMobile(username)) { // 用户名如果为手机号，则手机号登录
            user.setPhone(username);
            User u = restTemplate.postForObject(REST_URL_PREFIX + "user/findByUserCondition/", user, User.class);
            if (u != null) {
                username = u.getUsername();
            }

        }
        user.setUsername(username);
        //校验用户是否存在
        User u = restTemplate.postForObject(REST_URL_PREFIX + "user/findByUserCondition/", user, User.class);
        if (u != null && u.getPassword().equalsIgnoreCase(MD5Util.md5(u.getUsername() + password))) {
            rm.setStatus(FrontStatusConstants.ALREADY_EXIST_OF_USERNAME);
            rm.setCode("Fail");
            logger.info("======> User login find user by name is null !");
            return rm;
        }

        // 获取token
        String token = restTemplate.getForObject(REST_URL_PREFIX + "user/generateUserToken/" + username, String.class);
        res.put("token", token);
        res.put("userName", u.getUsername());
        res.put("id", u.getId());
        rm.setBody(res);
        return rm;
    }

    /**
     * 登出
     *
     * @param request
     * @return
     */
    @RequestMapping("/user/logout")
    public ResultMap<Map<Object, Object>> logout(HttpServletRequest request) {
        ResultMap<Map<Object, Object>> rm = new ResultMap<>();
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setBody(tokenmap);
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        Boolean b = restTemplate.getForObject(REST_URL_PREFIX + "user/redisDelToken/" + token, Boolean.class);
        if (!b) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        return rm;

    }

    @RequestMapping("/user/userSecure")
    public ResultMap<User> getUserSecure(HttpServletRequest request) {
        ResultMap<User> rm = new ResultMap<>();
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.USELESS_TOKEN);
            return rm;
        }
        Integer id = (Integer) tokenmap.get("id");
        User u = restTemplate.getForObject(REST_URL_PREFIX + "user/getUserById/" + id, User.class);
        rm.setBody(u);
        if (u == null) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        return rm;
    }


    @RequestMapping("/account/accountHomepage")
    public ResultMap<UserAcount> getAccountHomepage(HttpServletRequest request) {
        String token = request.getHeader("token");
        ResultMap<UserAcount> rm = new ResultMap<>();

        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN); // 15代表redis找不到这个用户登录信息
            return rm;
        }
        Integer userId = (Integer) tokenmap.get("id");
        UserAcount u = restTemplate.getForObject(REST_URL_PREFIX + "account/accountHomepage/" + userId, UserAcount.class);
        rm.setBody(u);
        if (u == null) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        return rm;
    }

    @RequestMapping("/user/userSecureDetailed")
    public ResultMap<User> getUserSecureDeatiled(HttpServletRequest request){

        ResultMap<User> rm= new ResultMap<>();
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        Integer id = (Integer) tokenmap.get("id");
        User u = restTemplate.getForObject(REST_URL_PREFIX + "user/getUserById/" + id, User.class);
        rm.setBody(u);
        if (u == null) {
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        return rm;
    }

}